import cv2
import numpy as np

img_O = cv2.imread(r'C:\Users\Public\opencv\Figure\jianzhu.jpg')
img_T = cv2.imread(r"C:\Users\Public\opencv\Figure\lena.png")

cv2.imshow('Origin image', img_O)
cv2.imshow('Target image', img_T)

color = ('r', 'g', 'b')
for i, col in enumerate(color):
    hist1, bins = np.histogram(img_O[:, :, i].ravel(), 256, [0, 256])
    hist2, bins = np.histogram(img_T[:, :, i].ravel(), 256, [0, 256])

    cdf1 = hist1.cumsum()  # 灰度值0-255的累计值数组
    cdf2 = hist2.cumsum()
    cdf1_hist = hist1.cumsum() / cdf1.max()  # 灰度值的累计值的比率
    cdf2_hist = hist2.cumsum() / cdf2.max()

    diff_cdf = [[0 for j in range(256)] for k in range(256)]
    # diff_cdf 里是每2个灰度值比率间的差值
    for j in range(256):
        for k in range(256):
            diff_cdf[j][k] = abs(cdf1_hist[j] - cdf2_hist[k])

    lut = [0 for j in range(256)]  # 映射表
    for j in range(256):
        min = diff_cdf[j][0]
        index = 0
        for k in range(256):  # 直方图规定化的映射原理
            if min > diff_cdf[j][k]:
                min = diff_cdf[j][k]
                index = k
        lut[j] = ([j, index])

    h = int(img_O.shape[0])
    w = int(img_O.shape[1])
    for j in range(h):  # 对原图像进行灰度值的映射
        for k in range(w):
            img_O[j, k, i] = lut[img_O[j, k, i]][1]

img_S = img_O  # 显示规定化后的图像
cv2.imshow('Specification image', img_S)
cv2.waitKey(0)
cv2.destroyAllWindows()
